
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;


/**
 * @author Amandine
 *
 */
public class CrazyReader extends Frame {

	private static final long serialVersionUID = 1L;
	
	public TextArea text;
	public TextField data;
	SharedObject sentence;
	public static String myName = "";
	public static int top ;
	
	
	/**
	 * @param argv
	 */
	public static void main(String argv[]) {
		if (argv.length != 1) {
			System.out.println("java CrazyReader <name>");
			return;
		}
		myName = argv[0];

		// initialize the system
		Client.init();

		// look up the CRAZY_READER object in the name server
		// if not found, create it, and register it in the name server
		SharedObject s = Client.lookup("CRAZY");
		if (s == null) {
			s = Client.create(new Sentence(myName));
			Client.register("CRAZY", s);
		}
		// create the graphical part
		new CrazyReader(s);
	}

	
	public CrazyReader(SharedObject s) {

		setLayout(new FlowLayout());

		text = new TextArea(10, 60);
		text.setEditable(false);
		text.setForeground(Color.red);
		add(text);

		data = new TextField(60);
		add(data);

		JButton start_button = new JButton("start");
		start_button
				.addActionListener(new CrazyReadListener(this, start_button));
		add(start_button);

		setSize(470, 300);
		text.setBackground(Color.white);
		show();

		sentence = s;
	}
}

class CrazyReadListener implements ActionListener {
	CrazyReader cR;
	JButton start_button;	

	public CrazyReadListener(CrazyReader c, JButton button) {
		this.cR = c;
		this.start_button = button;
	}

	public void actionPerformed(ActionEvent e) {
		
		if (CrazyReader.top == 0) {
			start_button.setText("Stop");
			new ActionCrazyReader(cR).start();
		} else {
			CrazyReader.top = 0;
			start_button.setText("Start");
		}
		
	}
}

class ActionCrazyReader extends Thread {

	CrazyReader cR;

	public ActionCrazyReader(CrazyReader cR) {
		this.cR = cR;
	}

	@Override
	public void run() {
		CrazyReader.top = 1;
		while (CrazyReader.top == 1) {
			try {
				sleep(500);				
				
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			// lock the object in read mode
			cR.sentence.lock_read();
			
			// invoke the method
			String s = ((Sentence) cR.sentence.obj).read();

			// unlock the object
			cR.sentence.unlock();

			// display the read value
			cR.text.append(s+"\n");

		}
	}
}
